<template>
	<el-dialog title="新增" :visible.sync="dialogVisible" width="80%">
		<el-form ref="form" label-width="80px">
			<el-form-item label="景点名字">
				<el-input v-model="form.name"></el-input>
			</el-form-item>
			<el-form-item label="摘要">
				<el-input v-model="form.description"></el-input>
			</el-form-item>
			<!-- 文件上传组件没有使用Axios，所以不能自动的拼接后端地址
			     不能用Axios请求拦截发送Token-->
			<el-form-item label="封面图">
				<el-upload class="avatar-uploader" :action="serverAddress+'uploadImg'"
					:headers="{adminToken:adminToken}" :show-file-list="false" :on-success="handleAvatarSuccess"
					:before-upload="beforeAvatarUpload">
					<img v-if="form.image" :src="form.image" class="avatar">
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
				</el-upload>
			</el-form-item>
			<el-form-item label="开始日期">
				<el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="form.openingHours"
					style="width: 100%;"></el-date-picker>
			</el-form-item>
			<el-form-item label="文章内容">
				<mavon-editor ref="contentEditor" v-model="form.content" :toolbars="toolbars" @imgAdd="(pos, file) => imgAdd(pos, file, 'content')"
					@imgDel="(pos) => imgDel(pos, 'content')" />
			</el-form-item>
			<el-form-item label="交通建议">
				<mavon-editor ref="transportEditor" v-model="form.transportation" :toolbars="toolbars" @imgAdd="(pos, file) => imgAdd(pos, file, 'transport')"
					@imgDel="(pos) => imgDel(pos, 'transport')" />
			</el-form-item>
			<el-form-item label="票价">
				<el-input v-model="form.ticketPrice" placeholder="请输入数字">
					<template #append>元</template>
				</el-input>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false">取 消</el-button>
			<el-button type="primary" @click="save()">保存</el-button>
		</span>
	</el-dialog>
</template>

<script>
	import ElementUI from 'element-ui';
	export default {
		data() {
			return {
				contentToolbars: { /* 文章内容编辑器工具栏配置 */ },
				transportToolbars: { /* 交通建议编辑器工具栏配置 */ },
				dialogVisible: false,
				newsType: [],
				serverAddress: "http://101.34.72.60:8088/adminApi/attractions/",
				adminToken: sessionStorage.getItem("adminToken"),
				toolbars: {
					bold: true, // 粗体
					italic: true, // 斜体
					header: true, // 标题
					underline: true, // 下划线
					strikethrough: true, // 中划线
					mark: true, // 标记
					quote: true, // 引用
					ol: true, // 有序列表
					ul: true, // 无序列表
					link: true, // 链接
					imagelink: true, // 图片链接
					code: true, // code
					table: true, // 表格
					fullscreen: true, // 全屏编辑
					readmodel: true, // 沉浸式阅读
					htmlcode: true, // 展示 html 源码
					help: true, // 帮助
					undo: true, // 上一步
					redo: true, // 下一步
					trash: true, // 清空
					navigation: true, // 导航目录
					subfield: true, // 单双栏模式
					preview: true // 预览
				},
				form: {
					name: '',
					content: '',
					image: '',
					description: '',
					openingHours: '',
					ticketPrice: '',
					transportation: ''
				},
				rules: {
					ticketPrice: [{
							required: true,
							message: '请输入票价',
							trigger: 'blur'
						},
						{
							pattern: /^\d+(\.\d{1,2})?$/,
							message: '请输入正确的数字格式',
							trigger: 'blur'
						}
					]
				}
			}
		},
		methods: {
			imgAdd(pos, file, editorType) {
			    var formdata = new FormData();
			    formdata.append('file', file);
			    
			    // 根据编辑器类型选择正确的ref
			    const editorRef = editorType === 'content' 
			        ? this.$refs.contentEditor 
			        : this.$refs.transportEditor;
			        
			    this.$http({
			        url: this.serverAddress + 'uploadImg',
			        data: formdata,
			        method: "post",
			        headers: {
			            'Content-Type': 'multipart/form-data',
			            'adminToken': this.adminToken
			        },
			        timeout: 60000
			    }).then((resp) => {
			        // 使用正确的编辑器引用
			        editorRef.$img2Url(pos, resp.data.data);
			    }).catch((error) => {
			        console.error('图片上传失败:', error);
			        this.$message.error('图片上传失败，请重试');
			    });
			},
			
			imgDel(pos, editorType) {
			    var imgUrl = pos[0];
			    alert(imgUrl);
			    
			    // 根据编辑器类型选择正确的ref
			    const editorRef = editorType === 'content' 
			        ? this.$refs.contentEditor 
			        : this.$refs.transportEditor;
			        
			    this.$http.get("adminApi/attractions/deleteImg", {
			        params: {
			            imgUrl: JSON.stringify(imgUrl)
			        }
			    }).then((res) => {
			        if (res.code == 200) {
			            // 使用正确的编辑器引用删除图片
			            editorRef.$imgDel(pos);
			            this.$message({
			                message: res.message,
			                type: 'success'
			            });
			        } else {
			            this.$message.error(res.message || '删除图片失败');
			        }
			    }).catch((error) => {
			        console.error('删除图片请求失败:', error);
			        this.$message.error('网络错误，删除失败');
			    });
			},
			handleAvatarSuccess(res, file) {
				if (res.code == 500) {
					ElementUI.Message({
						message: res.message,
						type: "error"
					})
				}
				if (res.code == 200) {

					this.form.image = res.data; //接收后端响应回来的地址
				}
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			save() {
				this.$http.post("adminApi/attractions/save", this.form).then((resp) => {
					if (resp.data.code == 200) {
						this.$message({
							duration: 500,
							message: resp.data.message,
							type: 'success',
							onClose: () => {
								this.dialogVisible = false; //关闭对话框
								this.$router.go(0); //更新当前路由地址
							}
						});
					}
				})
			}
		},
		mounted() {
			// //向后端发送请求，查询信息
			// this.$http.get("adminApi/newsCtl/newsType").then((resp) => {
			// 	if (resp.data.code == 200) {
			// 		this.newsType = resp.data.data;
			// 	}
			// })
		}
	}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 60px;
		height: 60px;
		line-height: 60px;
		text-align: center;
	}

	.avatar {
		width: 60px;
		height: 60px;
		display: block;
	}
</style>